package com.ax.center.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.ax.center.annotation.Logging;
import com.ax.center.dto.ApiResponse;
import com.ax.center.dto.LoginDTO;
import com.ax.center.dto.CO;
import com.ax.center.entity.UserLogin;
import com.ax.center.entity.Users;
import com.ax.center.mapper.LoginDTOMapper;
import com.ax.center.mapper.LoginMapper;
import com.ax.center.service.*;
import com.ax.center.urils.UserHolder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ax.center.urils.RedisContants.LOGIN_USER_KEY;
import static com.ax.center.urils.RedisContants.LOGIN_USER_TTL;

/**
 * @author zy
 * @date 2023/7/4 9:14
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper,UserLogin> implements LoginService {

    @Autowired
    private UsersService usersService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private LoginDTOMapper loginDTOMapper;


    @ApiOperation("登录")
    @Override
    public ApiResponse login(Long id, String password)  {
        Users user = usersService.checkPW(id, password);
       if(user==null){
            return  ApiResponse.fail("账号或者密码错误");
       }
        Long staffId = user.getStaffId();
        LoginDTO loginDTO = loginDTOMapper.getUserDetailsByStaffId(staffId);
//        String token= UUID.randomUUID().toString(true);
        String token= "ax_sx";
        CO CO = BeanUtil.copyProperties(user, CO.class);
        UserHolder.setUserHolder(CO);
        Map<String, Object> userMap = BeanUtil.beanToMap(CO,new HashMap<>(),CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        String key=LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(key,userMap);
        stringRedisTemplate.expire(key,LOGIN_USER_TTL, TimeUnit.HOURS);
        return ApiResponse.ok(loginDTO);
    }
}
